<template>
  <div class="bg-gradient-to-b from-sky-50 to-white rounded-lg shadow-lg p-6 overflow-hidden relative">
    <!-- 背景装饰保持不变 -->
    <div class="absolute top-0 right-0 w-80 h-80 bg-indigo-100 rounded-full filter blur-3xl opacity-20 translate-x-1/3 -translate-y-1/3"></div>
    <div class="absolute bottom-0 left-0 w-72 h-72 bg-sky-100 rounded-full filter blur-3xl opacity-20 -translate-x-1/3 translate-y-1/3"></div>

    <!-- 标题区保持不变 -->
    <h2 class="text-xl font-semibold text-gray-800 mb-8 relative z-10 flex items-center">
      <span class="w-1.5 h-7 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-3"></span>
      个人信息管理
      <span class="ml-2 text-sm font-normal text-gray-500 bg-sky-100 px-2 py-0.5 rounded-full">基础信息设置</span>
    </h2>

    <!-- 主布局：调整栅格比例适配大头像 -->
    <div class="flex flex-col md:flex-row gap-8 relative z-10 items-start">
      <!-- 头像区域：放大尺寸 + 优化间距 -->
      <div class="w-full md:w-2/5"> <!-- 左侧占比提升，适配大头像 -->
        <div class="text-center mb-8"> <!-- 整体间距优化 -->
          <!-- 头像容器：放大至40px + 渐变边框优化 -->
          <div class="w-40 h-40 rounded-full mx-auto mb-4 relative group"> <!-- 尺寸放大，margin调整 -->
            <div class="absolute inset-0 rounded-full bg-gradient-to-br from-sky-500 to-indigo-600 p-0.5 group-hover:scale-105 transition-transform z-[-1]"></div>
            <div class="w-full h-full rounded-full bg-white overflow-hidden">
              <img :src="userInfo.avatar" alt="用户头像" class="w-full h-full object-cover">
            </div>
          </div>
          
          <!-- 按钮容器：垂直排列按钮 -->
          <div class="flex flex-col items-center space-y-3">
            <!-- 更换头像按钮 -->
            <label class="cursor-pointer w-full max-w-[160px]">
              <input
                  type="file"
                  accept="image/png,image/gif"
                  @change="handleAvatarUpload"
                  class="hidden"
              />
              <span class="flex items-center justify-center bg-sky-50 text-gradient bg-clip-text text-transparent bg-gradient-to-r from-sky-600 to-indigo-600 px-4 py-2 rounded-md text-sm font-medium hover:bg-sky-100 transition-colors w-full">
                <font-awesome-icon icon="camera" class="mr-1" /> 更换头像
              </span>
            </label>
            
            <!-- 修改密码按钮 -->
            <button
                @click="showPasswordDialog = true"
                class="flex items-center justify-center px-4 py-2 bg-gradient-to-r from-sky-500 to-indigo-600 text-white rounded-md hover:from-sky-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow text-sm font-medium w-full max-w-[160px]"
            >
              <font-awesome-icon icon="key" class="mr-1" /> 修改密码
            </button>
          </div>
        </div>
      </div>

      <!-- 表单区域：适配左侧比例 -->
      <div class="w-full md:w-3/5"> <!-- 右侧占比对应左侧，保持布局平衡 -->
        <form class="space-y-6">
          <!-- 基础信息分组（保持原有结构，仅布局适配） -->
          <div>
            <h3 class="text-base font-medium text-gray-700 mb-4 flex items-center">
              <span class="w-1 h-4 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-2"></span>
              基础信息
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- 原有输入框保持不变 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">姓名</label>
                <input
                    type="text"
                    v-model="userInfo.username"
                    class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-gradient focus:border-transparent transition-all"
                    style="--tw-ring-gradient: linear-gradient(to right, #0ea5e9, #4f46e5)"
                >
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1.5">手机号码</label>
                <input
                    type="tel"
                    v-model="userInfo.phone"
                    class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-gradient focus:border-transparent transition-all"
                    style="--tw-ring-gradient: linear-gradient(to right, #0ea5e9, #4f46e5)"
                >
              </div>
            </div>
          </div>

          <!-- 企业信息分组（保持原有结构） -->
          <div>
            <h3 class="text-base font-medium text-gray-700 mb-4 flex items-center">
              <span class="w-1 h-4 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-2"></span>
              企业信息
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <!-- 原有输入框/下拉框保持不变 -->
              <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1.5">电子邮箱</label>
                <input
                    type="email"
                    v-model="userInfo.email"
                    class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-gradient focus:border-transparent transition-all"
                    style="--tw-ring-gradient: linear-gradient(to right, #0ea5e9, #4f46e5)"
                >
              </div>
              <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1.5">单位/公司</label>
                <input
                    type="text"
                    v-model="userInfo.unit"
                    class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-gradient focus:border-transparent transition-all"
                    style="--tw-ring-gradient: linear-gradient(to right, #0ea5e9, #4f46e5)"
                >
              </div>
              <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700 mb-1.5">所属行业</label>
                <select
                    v-model="userInfo.industry"
                    class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-gradient focus:border-transparent transition-all appearance-none bg-white"
                    style="--tw-ring-gradient: linear-gradient(to right, #0ea5e9, #4f46e5)"
                >
                  <option value="">请选择行业</option>
                  <option value="IT">信息技术</option>
                  <option value="finance">金融</option>
                  <option value="education">教育</option>
                  <option value="medical">医疗健康</option>
                  <option value="other">其他行业</option>
                </select>
              </div>
            </div>
          </div>

          <!-- 按钮区域保持不变 -->
          <div class="flex justify-end space-x-3 pt-4 border-t border-sky-50">
            <button
                type="button"
                class="px-4 py-2 border border-sky-200 text-gray-700 rounded-md hover:bg-sky-50 transition-colors"
            >
              取消
            </button>
            <button
                type="button"
                @click="saveProfile"
                class="px-4 py-2 bg-gradient-to-r from-sky-500 to-indigo-600 text-white rounded-md hover:from-sky-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow"
            >
              <font-awesome-icon icon="save" class="mr-1" /> 保存修改
            </button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 修改密码弹窗 -->
    <div v-if="showPasswordDialog" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md">
        <div class="px-6 py-4 border-b border-gray-200">
          <h3 class="text-lg font-medium text-gray-900">修改密码</h3>
        </div>
        <div class="px-6 py-4">
          <form @submit.prevent="changePassword" class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">旧密码</label>
              <input
                  v-model="passwordForm.oldPassword"
                  type="password"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500"
                  placeholder="请输入旧密码"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
              <input
                  v-model="passwordForm.newPassword"
                  type="password"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500"
                  placeholder="请输入新密码"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
              <input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  required
                  class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500"
                  placeholder="请再次输入新密码"
              >
            </div>
          </form>
        </div>
        <div class="px-6 py-4 border-t border-gray-200 flex justify-end space-x-3">
          <button
              @click="showPasswordDialog = false"
              class="px-4 py-2 border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50"
          >
            取消
          </button>
          <button
              @click="changePassword"
              class="px-4 py-2 bg-gradient-to-r from-sky-500 to-indigo-600 text-white rounded-md hover:from-sky-600 hover:to-indigo-700"
          >
            确认修改
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getProfileApi, updateProfileApi, uploadAvatarApi} from '@/api/user.js'
import {ElMessage} from 'element-plus'
import request from '@/api/request.js'

export default {
  data() {
    return {
      userInfo: {
        id: null,
        username: '',
        phone: '',
        email: '',
        unit: '', // 修改为company以匹配前端绑定
        industry: '',
        avatar: ''
      },
      loading: false,
      // 添加密码修改相关数据
      showPasswordDialog: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      }
    }
  },
  async mounted() {
    await this.loadProfile()
  },
  methods: {
    async loadProfile() {
      this.loading = true
      try {
        const res = await getProfileApi()
        if (res.code === 200) {
          const user = res.data
          this.userInfo = {
            id: user.id,
            username: user.username || '',
            phone: user.phone || '',
            email: user.email || '',
            unit: user.unit || '', // 根据实际返回字段调整
            industry: user.industry || '',
            avatar: user.image
                ? 'http://localhost:8088/api' + user.image.replace('http://localhost:8088', '') // 去掉多余的前缀
                : 'https://picsum.photos/id/64/200/200'
          }
          console.log('>>> 更新后的头像URL:', this.userInfo.avatar)
        } else {
          ElMessage.error(res.msg || '加载失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请重试')
        console.error('加载用户信息失败:', error)
      } finally {
        this.loading = false
      }
    },

    async saveProfile() {
      try {
        const data = {
          id: this.userInfo.id,
          username: this.userInfo.username,   // 使用正确的字段名
          phone: this.userInfo.phone,
          email: this.userInfo.email,
          unit: this.userInfo.unit,     // 确保使用了正确的字段映射
          industry: this.userInfo.industry
        }

        console.log('准备发送的数据:', data) // 调试用

        const res = await updateProfileApi(data)
        if (res.code === 200) {
          ElMessage.success('保存成功')
          await this.loadProfile() // 保存成功后重新加载，确保界面数据是最新的
        } else {
          ElMessage.error(res.msg || '保存失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请重试')
        console.error('保存失败:', error)
      }
    },

    async handleAvatarUpload(event) {
      const file = event.target.files[0]
      if (!file) return

      const formData = new FormData()
      formData.append('avatar', file)

      try {
        const res = await uploadAvatarApi(file)
        if (res.code === 200) {
          ElMessage.success('头像上传成功')
          await this.loadProfile() // 上传成功后重新加载用户信息以更新头像URL
        } else {
          ElMessage.error(res.msg || '上传失败')
        }
      } catch (error) {
        ElMessage.error('上传失败，请重试')
        console.error('头像上传失败:', error)
      }
    },

    // 添加修改密码的方法
    async changePassword() {
      // 验证新密码和确认密码是否一致
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        ElMessage.error('新密码与确认密码不一致')
        return
      }

      // 验证密码长度
      if (this.passwordForm.newPassword.length < 6 || this.passwordForm.newPassword.length > 32) {
        ElMessage.error('新密码长度需在6-32位之间')
        return
      }

      try {
        const data = {
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword
        }

        // 发送修改密码请求
        const res = await request({
          url: 'api/user/update/changePassword',
          method: 'put',
          data
        })

        if (res.code === 200) {
          ElMessage.success('密码修改成功')
          // 清除本地存储的认证信息
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          // 重定向到登录页面
          this.$router.push('/login')
        } else {
          ElMessage.error(res.msg || '密码修改失败')
        }
      } catch (error) {
        ElMessage.error('网络错误，请重试')
        console.error('密码修改失败:', error)
      }
    }
  }
}
</script>